<?php

class PayController extends Uuch_BaseController {

    public function indexAction() {
        
    }

    const TYPE_RECHANGE = 1;
    const TYPE_ORDER = 2;
    const TYPE_WAYBILL = 3;

    /**
     * 汇兑损失 
     */
    const DISCOUNT_RATE = 1.03;

    /**
     * 支付发起页 
     */
    public function payingAction() {
        $this->checkLogin();
        $this->appendCss('/css/home/pay.css');
        $type = $this->getRequest()->getParam('type');
        $this->appendScript('/js/jquery.min.js');
        $id = $this->getRequest()->getParam('id');
        if ($type == NULL || $type == '') {
            $type = substr($id, strlen($id) - 1);
            $id = substr($id, 0, strlen($id) - 1);
        }
        $payer = $this->createPayer($type, $id);
        if ($payer == NULL) {
            throw new Exception('没有找到对应的付款对象,请联系网站管理员');
        }
        if (!$payer->canPay($this->currentUser()->Id)) {
            $this->redirect('home', 'member');
            return;
        }

        $name = $payer->getPayName();
        $money = $payer->getMoney();

        $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/config.ini', APPLICATION_ENV);

        $this->view->paypal = $config->paypalurl;
        $this->view->account = $config->account;
        $this->view->host = $config->host;

        $this->setTitle('支付' . $name);

        $rate = Application_Model_Config::getRate()->Value;
        $this->view->payer = $payer;
        $this->view->accountMoney = $this->currentUser()->getAccount()->Money;
        $this->view->type = $type;
        $this->view->name = $name;
        $this->view->id = $id;
        $this->view->billNo = $payer->getBillNo();
        $this->view->money = $money;
        $this->view->rate = $rate;
        $this->view->CCusd = number_format($this->getusd($money, $rate, "CreditCard"), 2);
        $this->view->CCpartUsd = number_format($this->getusd($money - $this->view->accountMoney, $rate, "CreditCard"), 2);
        $this->view->PPusd = number_format($this->getusd($money, $rate, "PayPal"), 2);
        $this->view->PPpartUsd = number_format($this->getusd($money - $this->view->accountMoney, $rate, "PayPal"), 2);
        $this->view->count = $this->getSafeParam('count');
    }

    /**
     * 返回一个支付单
     * @param type $type
     * @param type $id
     * @return Application_Model_PayInterface 
     */
    public function createPayer($type, $id) {
        return Application_Model_PayBill::createPayer($type, $id);
    }

    /**
     * 使用余额支付 
     */
    public function paidAction() {
        $type = $this->getRequest()->getParam('type');
        $id = $this->getRequest()->getParam('id');

        $payer = $this->createPayer($type, $id);

        if (!$payer->canPay($this->currentUser()->Id)) {
            $this->redirect('home', 'member');
            return;
        }

        $money = $payer->getMoney();
        $beforeMoney = $this->currentUser()->getAccount()->Money;
        $bill = $this->savePaybill($money, 0, $type, Application_Model_PayBill::PAY_ACCOUNT, $id, '直接从帐户支付');
        $this->payMoney($id, $type, $this->currentUser()->getAccount());
        $account = $this->currentUser()->getAccount();
        $this->_addTransaction('', $bill, $beforeMoney, $account);
        $this->redirect('success', null, array('pid' => $bill->Id));
    }

    /**
     * 支付金额
     * @param type $id
     * @param type $type
     * @param Application_Model_Account $account 
     */
    private function payMoney($id, $type, $account) {
        $payer = $this->createPayer($type, $id);
        $money = $payer->getMoney();
        if (method_exists($payer, 'getPayMoney')) {
            $money = $payer->getPayMoney();
        }
        $this->AnalysisPayStatus($id, $money, $payer, $account->Id);
        $account->pay($money, $payer);
    }

    private function AnalysisPayStatus($id, $money, $payer, $userId) {
        if (!($payer->isRepeatPay())) {
            Application_Model_FinancialCheckItem::addCheckItem(Application_Model_DomainobjectType::ObjectType_Pay, $id, $money, $payer->getPayCommen() . "二次支付", "Admin", $userId, Application_Model_FinancialCheckItem::Money_twoPay);
        }
    }

    /**
     * Paypal回调页面 
     */
    public function notifyAction() {

        $ipn = new Uuch_PayPal();

        $status = $ipn->processIPN();
        if ($status == 0) {
            $pid = $this->getRequest()->getParam('pid');
            $paybill = Application_Model_PayBill::load($pid);
            $txnId = $this->getRequest()->getParam('txn_id');

            if ($paybill->Status == Application_Model_PayBill::PAY_STATUS_SUCCESS) {
                $this->_log('重复的Notify', Zend_Log::INFO);
                if($paybill->txnId != $txnId){
                    $payer = $this->createPayer($paybill->type, $paybill->DomainId);
                    Application_Model_FinancialCheckItem::addCheckItem(Application_Model_DomainobjectType::ObjectType_Pay, $paybill->DomainId, $paybill->Money, $payer->getPayCommen() . "二次支付($txnId)", "Admin", $paybill->AccountId, Application_Model_FinancialCheckItem::Money_twoPay);
                }
                $this->_helper->redirector('success');
                return;
            }
            $paybill->txnId = $txnId;
            $account = Application_Model_UserAccount::load($paybill->AccountId);
            $beforeMoney = $account->Money;
            //充值到帐户
            $account->recharge($paybill);

            if ($paybill->Type != PayController::TYPE_RECHANGE) {

                //从帐户中扣除相应的订单金额
                $this->payMoney($paybill->DomainId, $paybill->Type, $account);
            } else {
                $rbill = Application_Model_RechargeBill::load($paybill->DomainId);
                $rbill->setPaid();
                $rbill->save();
            }
            // 对接财务模块
            $this->_addTransaction($paybill->txnId, $paybill, $beforeMoney, $account);
            $this->_helper->redirector('success');
        }
        $this->json(FALSE);
    }

    /**
     * 返回美元
     * @param type $money
     * @param type $rate
     * @return type 
     */
    private function getusd($money, $rate, $type) {
        $discount = Application_Model_Config::getDiscountRate()->Value;
        if ($type == "CreditCard") {
            return round(($money * ($discount + 0.01) ) / $rate, 2);
        } else if ($type == "PayPal") {
            return round(($money * $discount ) / $rate, 2) + 0.3;
        }
    }

    /**
     * Paypal支付跳转页
     */
    public function paypalAction() {
        //require_once(APPLICATION_PATH . '/../library/pay/Paypal.php');     

        $type = $this->getRequest()->getParam('type');
        $domainId = $this->getRequest()->getParam('domainId');
        $payer = $this->createPayer($type, $domainId);
        $money = $payer->getMoney();
        if ($this->getSafeParam('useAccount') == 'true') {
            $money = $money - $this->currentUser()->Account->Money;
        }
        if ($money < 0) {
            $this->redirect('paying', 'pay', array('type' => $type, 'id' => $domainId));
            return;
        }
        $rate = Application_Model_Config::getRate()->Value;

        $usmoney = $this->getusd($money, $rate, "PayPal");

        $bill = $this->savePaybill($money, $usmoney, $type, Application_Model_PayBill::PAY_PAYPAL, $domainId, 'Paypal支付');

        $this->view->itemname = $payer->getPayName();
        $this->view->bill = $bill;
        $this->_helper->layout->disableLayout();
        /*
          //Our request parameters
          $requestParams = array(
          'RETURNURL' => "http://test.uuch.com/Pay/success",
          'CANCELURL' => 'http://test.uuch.com/Pay/cancell',
          'NOTIFYURL'=>'http://test.uuch.com/Pay/callback'
          );

          $orderParams = array(
          'PAYMENTREQUEST_0_AMT' => $usmoney,
          'PAYMENTREQUEST_0_SHIPPINGAMT' => '0',
          'PAYMENTREQUEST_0_CURRENCYCODE' => 'USD',
          'PAYMENTREQUEST_0_ITEMAMT' => $usmoney
          );

          $item = array(
          'L_PAYMENTREQUEST_0_NAME0' => '运费',
          'L_PAYMENTREQUEST_0_DESC0' => '提交运费',
          'L_PAYMENTREQUEST_0_AMT0' => $usmoney,
          'L_PAYMENTREQUEST_0_QTY0' => '1'
          );

          $paypal = new Paypal();
          $response = $paypal -> request('SetExpressCheckout',$requestParams + $orderParams + $item);

          if(is_array($response) && $response['ACK'] == 'Success') { //Request successful
          $token = $response['TOKEN'];
          $this->_redirect('https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=' . urlencode($token));
          }  else {
          throw new Exception("paypal 错误");
          }
         * 
         */
    }

    /**
     * 国际信用卡支付
     */
    public function cardAction() {
        $type = $this->getRequest()->getParam('type');
        $domainId = $this->getRequest()->getParam('domainId');
        $jsreturn = str_replace(" ", "", $this->getRequest()->getParam('jsreturn'));
        $payer = $this->createPayer($type, $domainId);
        $money = $payer->getMoney();
        if ($this->getSafeParam('useAccount') == 'true') {
            $money = $money - $this->currentUser()->Account->Money;
        }
        if ($money < 0) {
            $this->redirect('paying', 'pay', array('type' => $type, 'id' => $domainId));
            return;
        }
        $rate = Application_Model_Config::getRate()->Value;

        $usmoney = $this->getusd($money, $rate, "CreditCard");

        $bill = $this->savePaybill($money, $usmoney, $type, Application_Model_PayBill::PAY_CARD, $domainId, '国际信用卡支付');

        $this->view->itemname = $payer->getPayName();
        $this->view->bill = $bill;
        $this->view->jsreturn = $jsreturn;
        $this->view->back = $this->getSafeParam('card');
        $this->_helper->layout->disableLayout();
    }

    /**
     * 支付宝和财付通支付 跳转页
     */
    public function chinapayAction() {
        require_once(APPLICATION_PATH . '/../library/pay/uuchPay.php');
        $type = $this->getRequest()->getParam('type');
        $domainId = $this->getRequest()->getParam('domainId');
        $payer = $this->createPayer($type, $domainId);
        $money = $payer->getMoney();
        if ($this->getSafeParam('useAccount') == 'true') {
            $money = $money - $this->currentUser()->Account->Money;
        }
        if ($money < 0) {
            $this->redirect('paying', 'pay', array('type' => $type, 'id' => $domainId));
            return;
        }
        $bill = $this->savePaybill($money, 0, $type, Application_Model_PayBill::PAY_ALIPAY, $domainId, '支付宝支付');
        $itemName = $payer->getMoney();

        $itemBody = $itemName;
        if ($this->getSafeParam("paytype")) {
            $payUrl = uuch_pay::aliPay($bill->Id, $itemName, $itemBody, $money);
        } else {
            $payUrl = uuch_pay::tenPay($bill->Id, $itemName, $itemBody, $money);
        }
        $this->_redirect($payUrl);
    }

    public function cardnotifyAction() {
        require_once(APPLICATION_PATH . '/../library/pay/card/alipay.config.php');
        require_once(APPLICATION_PATH . '/../library/pay/card/lib/alipay_notify.class.php');

        $this->_log('alipay verifynotify start:', Zend_Log::INFO);
        //计算得出通知验证结果
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        $this->_log('result:' . $verify_result, Zend_Log::INFO);
        //$verify_result=FALSE;
        //test
        //$verify_result=1;
        //$this->_log('verify_result:'.$verify_result,  Zend_Log::INFO);

        if ($verify_result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
            $out_trade_no = $_POST['out_trade_no']; //获取订单号
            $trade_no = $_POST['trade_no'];      //获取支付宝交易号
            $total = $_POST['price']; //获取总价格
            $trade_status = $_POST['trade_status'];             //获取状态
            //test
            //$out_trade_no='56';
            //$trade_no='2012101419427939';
            //$total='0.01';
            //$trade_status='TRADE_SUCCESS';

            $this->_log('trade_status:' . $_POST['trade_status'], Zend_Log::INFO);
            $this->_log("out_trade_no:$out_trade_no trade_no:$trade_no price:$total", Zend_Log::INFO);
            $paybill = Application_Model_PayBill::load($out_trade_no);

            if ($paybill->Status == Application_Model_PayBill::PAY_STATUS_SUCCESS) {
                $this->_log('重复的Notify', Zend_Log::INFO);
                if($paybill->txnId != $trade_no){
                    $payer = $this->createPayer($paybill->type, $paybill->DomainId);
                    Application_Model_FinancialCheckItem::addCheckItem(Application_Model_DomainobjectType::ObjectType_Pay, $paybill->DomainId, $paybill->Money, $payer->getPayCommen() . "二次支付($trade_no)", "Admin", $paybill->AccountId, Application_Model_FinancialCheckItem::Money_twoPay);
                }
                echo 'success';
                return;
            }

            if ($trade_status == 'WAIT_BUYER_PAY') {
                //该判断表示买家已在支付宝交易管理中产生了交易记录，但没有付款
                $this->_log('表示买家已在支付宝交易管理中产生了交易记录，但没有付款:' . $out_trade_no, Zend_Log::INFO);
                $paybill->Status = Application_Model_PayBill::PAY_STATUS_GOPAY;
                $paybill->TxnId = $trade_no;
                $paybill->save();
                //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                echo "success";
                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
            } else if ($trade_status == 'WAIT_SELLER_SEND_GOODS' || $trade_status == 'TRADE_SUCCESS') {
                //该判断表示买家已在支付宝交易管理中产生了交易记录且付款成功，但卖家没有发货                            
                $this->_log('表示买家已在支付宝交易管理中产生了交易记录且付款成功，但卖家没有发货:' . $out_trade_no, Zend_Log::INFO);

                $this->_log("paybill:$paybill->Id,account:$paybill->AccountId", Zend_Log::INFO);
                $user = Application_Model_User::load($paybill->AccountId);
                $account = $user->Account;
                $beforeMoney = $account->Money;
                $paybill->TxnId = $trade_no;
                //充值到帐户
                $account->recharge($paybill);
                $this->_log("paybill:$paybill->Id,account:$paybill->AccountId,Money:$account->Money", Zend_Log::INFO);

                if ($paybill->Type != Application_Model_PayBill::TYPE_RECHANGE) {
                    //从帐户中扣除相应的订单金额
                    $this->payMoney($paybill->DomainId, $paybill->Type, $account);
                } else {
                    $rbill = Application_Model_RechargeBill::load($paybill->DomainId);
                    $rbill->setPaid();
                    $rbill->save();
                }
                //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                // 对接财务模块
                $this->_addTransaction($paybill->txnId, $paybill, $beforeMoney, $account);
                echo "success";  //请不要修改或删除
                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
            } else if ($trade_status == 'WAIT_BUYER_CONFIRM_GOODS') {
                //该判断表示卖家已经发了货，但买家还没有做确认收货的操作
                $this->_log('该判断表示卖家已经发了货，但买家还没有做确认收货的操作:' . $out_trade_no, Zend_Log::INFO);
                //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                echo "success";  //请不要修改或删除
                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
            } else if ($trade_status == 'TRADE_FINISHED') {
                //该判断表示买家已经确认收货，这笔交易完成
                $this->_log('买家已经确认收货，这笔交易完成:' . $out_trade_no, Zend_Log::INFO);
                $paybill->Type = Application_Model_PayBill::PAY_STATUS_FINISH;
                $paybill->save();

                //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                echo "success";  //请不要修改或删除
                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
            } else {
                $this->_log('其他状态判断:' . $out_trade_no, Zend_Log::INFO);
                //其他状态判断
                echo "success";

                //调试用，写文本函数记录程序运行情况是否正常
                //logResult ("这里写入想要调试的代码变量值，或其他运行的结果记录");
            }

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        } else {
            $this->_log('验证失败:' . $out_trade_no, Zend_Log::INFO);
            //验证失败
            echo "fail";

            //调试用，写文本函数记录程序运行情况是否正常
            //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
        }
        $this->_helper->layout->disableLayout();
    }

    /**
     * 支付宝回调页
     * @return type 
     */
    public function alinotifyAction() {
        /*         * ***********************页面功能说明*************************
         * 创建该页面文件时，请留心该页面文件中无任何HTML代码及空格。
         * 该页面不能在本机电脑测试，请到服务器上做测试。请确保外部可以访问该页面。
         * 该页面调试工具请使用写文本函数logResult，该函数已被默认关闭，见alipay_notify_class.php中的函数verifyNotify
         * 如果没有收到该页面返回的 success 信息，支付宝会在24小时内按一定的时间策略重发通知

         * WAIT_BUYER_PAY(表示买家已在支付宝交易管理中产生了交易记录，但没有付款);
         * WAIT_SELLER_SEND_GOODS(表示买家已在支付宝交易管理中产生了交易记录且付款成功，但卖家没有发货);
         * WAIT_BUYER_CONFIRM_GOODS(表示卖家已经发了货，但买家还没有做确认收货的操作);
         * TRADE_FINISHED(表示买家已经确认收货，这笔交易完成);
         */
        require_once(APPLICATION_PATH . '/../library/pay/alipay/alipay_notify.class.php');
        require_once(APPLICATION_PATH . '/configs/alipay.config.php');

        $this->_helper->layout->disableLayout();
        $this->_log('alipay verifynotify start:', Zend_Log::INFO);
        //计算得出通知验证结果
        $alipayNotify = new AlipayNotify($aliapy_config);
        $verify_result = $alipayNotify->verifyNotify();

        //test
        //$verify_result=1;
        //$this->_log('verify_result:'.$verify_result,  Zend_Log::INFO);

        if ($verify_result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
            $out_trade_no = $_POST['out_trade_no']; //获取订单号
            $trade_no = $_POST['trade_no'];      //获取支付宝交易号
            $total = $_POST['price']; //获取总价格
            $trade_status = $_POST['trade_status'];             //获取状态
            //test
            //$out_trade_no='56';
            //$trade_no='2012101419427939';
            //$total='0.01';
            //$trade_status='TRADE_SUCCESS';

            $this->_log('trade_status:' . $_POST['trade_status'], Zend_Log::INFO);
            $this->_log("out_trade_no:$out_trade_no trade_no:$trade_no price:$total", Zend_Log::INFO);
            $paybill = Application_Model_PayBill::load($out_trade_no);
            if ($paybill->Money != $total) {
                $this->_log('充值价格不匹配:' . $out_trade_no, Zend_Log::ERR);
                echo 'success';
                return;
            }

            if ($paybill->Status == Application_Model_PayBill::PAY_STATUS_SUCCESS) {
                $this->_log('重复的Notify', Zend_Log::INFO);
                if($paybill->txnId != $trade_no){
                    $payer = $this->createPayer($paybill->type, $paybill->DomainId);
                    Application_Model_FinancialCheckItem::addCheckItem(Application_Model_DomainobjectType::ObjectType_Pay, $paybill->DomainId, $paybill->Money, $payer->getPayCommen() . "二次支付($trade_no)", "Admin", $paybill->AccountId, Application_Model_FinancialCheckItem::Money_twoPay);
                }
                echo 'success';
                return;
            }


            if ($trade_status == 'WAIT_BUYER_PAY') {
                //该判断表示买家已在支付宝交易管理中产生了交易记录，但没有付款
                $this->_log('表示买家已在支付宝交易管理中产生了交易记录，但没有付款:' . $out_trade_no, Zend_Log::INFO);
                $paybill->Status = Application_Model_PayBill::PAY_STATUS_GOPAY;
                $paybill->TxnId = $trade_no;
                $paybill->save();
                //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                echo "success";
                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
            } else if ($trade_status == 'WAIT_SELLER_SEND_GOODS' || $trade_status == 'TRADE_SUCCESS') {
                //该判断表示买家已在支付宝交易管理中产生了交易记录且付款成功，但卖家没有发货                            
                $this->_log('表示买家已在支付宝交易管理中产生了交易记录且付款成功，但卖家没有发货:' . $out_trade_no, Zend_Log::INFO);

                $this->_log("paybill:$paybill->Id,account:$paybill->AccountId", Zend_Log::INFO);
                $user = Application_Model_User::load($paybill->AccountId);
                $account = $user->Account;
                $paybill->TxnId = $trade_no;
                $beforeMoney = $account->Money;
                //充值到帐户

                $account->recharge($paybill);
                $this->_log("paybill:$paybill->Id,account:$paybill->AccountId,Money:$account->Money", Zend_Log::INFO);

                if ($paybill->Type != Application_Model_PayBill::TYPE_RECHANGE) {
                    //从帐户中扣除相应的订单金额
                    $this->payMoney($paybill->DomainId, $paybill->Type, $account);
                } else {
                    $rbill = Application_Model_RechargeBill::load($paybill->DomainId);
                    $rbill->setPaid();
                    $rbill->save();
                }
                // 对接财务模块
                $this->_addTransaction($paybill->txnId, $paybill, $beforeMoney, $account);

                //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                echo "success";  //请不要修改或删除
                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
            } else if ($trade_status == 'WAIT_BUYER_CONFIRM_GOODS') {
                //该判断表示卖家已经发了货，但买家还没有做确认收货的操作
                $this->_log('该判断表示卖家已经发了货，但买家还没有做确认收货的操作:' . $out_trade_no, Zend_Log::INFO);
                //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                echo "success";  //请不要修改或删除
                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
            } else if ($trade_status == 'TRADE_FINISHED') {
                //该判断表示买家已经确认收货，这笔交易完成
                $this->_log('买家已经确认收货，这笔交易完成:' . $out_trade_no, Zend_Log::INFO);
                $paybill->Type = Application_Model_PayBill::PAY_STATUS_FINISH;
                $paybill->save();

                //判断该笔订单是否在商户网站中已经做过处理（可参考“集成教程”中“3.4返回数据处理”）
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                echo "success";  //请不要修改或删除
                //调试用，写文本函数记录程序运行情况是否正常
                //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
            } else {
                $this->_log('其他状态判断:' . $out_trade_no, Zend_Log::INFO);
                //其他状态判断
                echo "success";

                //调试用，写文本函数记录程序运行情况是否正常
                //logResult ("这里写入想要调试的代码变量值，或其他运行的结果记录");
            }

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        } else {
            $this->_log('验证失败:' . $out_trade_no, Zend_Log::INFO);
            //验证失败
            echo "fail";

            //调试用，写文本函数记录程序运行情况是否正常
            //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
        }
    }
    /**
     * Paypal回调页面-- 测试模版
     */
    public function notifytestAction() {
        
        $ipn = new Uuch_PayPal();

//        $status = $ipn->processIPN();
//        if ($status == 0) {
            $pid = $this->getRequest()->getParam('pid');
            $paybill = Application_Model_PayBill::load($pid);
            $txnId = $this->getRequest()->getParam('txn_id');

            if ($paybill->Status == Application_Model_PayBill::PAY_STATUS_SUCCESS) {
                $this->_log('重复的Notify', Zend_Log::INFO);
                if($paybill->txnId != $txnId){
                    $payer = $this->createPayer($paybill->type, $paybill->DomainId);
                    Application_Model_FinancialCheckItem::addCheckItem(Application_Model_DomainobjectType::ObjectType_Pay, $paybill->DomainId, $paybill->Money, $payer->getPayCommen() . "二次支付($txnId)", "Admin", $paybill->AccountId, Application_Model_FinancialCheckItem::Money_twoPay);
                }
                $this->_helper->redirector('success');
                return;
            }
            $paybill->txnId = $txnId;
            $account = Application_Model_UserAccount::load($paybill->AccountId);
            $beforeMoney = $account->Money;
            //充值到帐户
            $account->recharge($paybill);

            if ($paybill->Type != PayController::TYPE_RECHANGE) {

                //从帐户中扣除相应的订单金额
                $this->payMoney($paybill->DomainId, $paybill->Type, $account);
            } else {
                $rbill = Application_Model_RechargeBill::load($paybill->DomainId);
                $rbill->setPaid();
                $rbill->save();
            }
            // 对接财务模块
            $this->_addTransaction($paybill->txnId, $paybill, $beforeMoney, $account);
            $this->_helper->redirector('success');
//        }
        $this->json(FALSE);
    }

    /**
     * 支付宝回调页 - 模拟测试
     * @return type 
     */
    public function alinotifytestAction() {
        
        require_once(APPLICATION_PATH . '/../library/pay/alipay/alipay_notify.class.php');
        require_once(APPLICATION_PATH . '/configs/alipay.config.php');

        $this->_helper->layout->disableLayout();
        $this->_log('alipay verifynotify start:', Zend_Log::INFO);
        $alipayNotify = new AlipayNotify($aliapy_config);
        $verify_result = $alipayNotify->verifyNotify();
//        if ($verify_result) {
//            exit;
//            return;
//        }
        $out_trade_no = $_POST['out_trade_no']; //获取订单号
        $trade_no = $_POST['trade_no'];      //获取支付宝交易号
        $total = $_POST['price']; //获取总价格
        $trade_status = $_POST['trade_status'];             //获取状态

        $this->_log('trade_status:' . $_POST['trade_status'], Zend_Log::INFO);
        $this->_log("out_trade_no:$out_trade_no trade_no:$trade_no price:$total", Zend_Log::INFO);
        $paybill = Application_Model_PayBill::load($out_trade_no);
        if ($paybill->Money != $total) {
            $this->_log('充值价格不匹配:' . $out_trade_no, Zend_Log::ERR);
            echo 'success';
            exit;
        }

        if ($paybill->Status == Application_Model_PayBill::PAY_STATUS_SUCCESS) {
            $this->_log('重复的Notify', Zend_Log::INFO);
            if($paybill->txnId != $trade_no){
                $payer = $this->createPayer($paybill->type, $paybill->DomainId);
                Application_Model_FinancialCheckItem::addCheckItem(Application_Model_DomainobjectType::ObjectType_Pay, $paybill->DomainId, $paybill->Money, $payer->getPayCommen() . "二次支付($trade_no)", "Admin", $paybill->AccountId, Application_Model_FinancialCheckItem::Money_twoPay);
            }
            echo 'success';
            exit;
        }
        if ($trade_status == 'WAIT_SELLER_SEND_GOODS' || $trade_status == 'TRADE_SUCCESS') {
            $this->_log('表示买家已在支付宝交易管理中产生了交易记录且付款成功，但卖家没有发货:' . $out_trade_no, Zend_Log::INFO);

            $this->_log("paybill:$paybill->Id,account:$paybill->AccountId", Zend_Log::INFO);
            $user = Application_Model_User::load($paybill->AccountId);
            $account = $user->Account;
            $paybill->TxnId = $trade_no;
            $periodStart = $account->Money;
            $account->recharge($paybill);
            $this->_log("paybill:$paybill->Id,account:$paybill->AccountId,Money:$account->Money", Zend_Log::INFO);

            if ($paybill->Type != Application_Model_PayBill::TYPE_RECHANGE) {
                $this->payMoney($paybill->DomainId, $paybill->Type, $account);
            } else {
                $rbill = Application_Model_RechargeBill::load($paybill->DomainId);
                $rbill->setPaid();
                $rbill->save();
            }
            $this->_addTransaction($trade_no, $paybill, $periodStart, $account);
            echo "success2";
        } 
        exit;
    }

    /**
     * 保存支付单
     * @param type $money 金额
     * @param type $usmoney 美元
     * @param type $type  1.充值  2.代购订单  3.运单 
     * @param type $payid 支付站点：1.paypal,2.alipay,3.tenpay
     * @param type $domainId 相关对应ID
     * @param type $desc 描述
     */
    private function savePaybill($money, $usmoney, $type, $payid, $domainId, $desc) {
        $desc = $this->AnalysisRechargeActivity($money, $type, $desc);
        $bill = new Application_Model_PayBill();
        $bill->AccountId = $this->currentUser()->Id;
        $bill->Money = $money;
        $bill->Status = Application_Model_PayBill::PAY_STATUS_CREATED;
        $bill->Type = $type;
        $bill->DateCreated = $this->now();
        $bill->Usmoney = $usmoney;
        $bill->Rate = Application_Model_Config::getRate()->Value;
        $bill->DiscountRate = Application_Model_Config::getDiscountRate()->Value;
        $bill->PayId = $payid;
        $bill->DomainId = $domainId;
        $bill->Description = $desc;
        $bill->save();
        return $bill;
    }

    /**
     *  充值活动判断
     */
    private function AnalysisRechargeActivity($money, $type, $desc) {
        $defalutCode = '4e6dc96b10041c0c37c5b33018d6f8f1';
        $requestCode = '';
        if(array_key_exists('fmRechangeCode', $_COOKIE)){
            $requestCode = Uuch_Util::decryptString($_COOKIE['fmRechangeCode']);
        }
        if (date("Y-m-d") >= Application_Model_RechargeBill::RechargeActivityStart && date("Y-m-d") < Application_Model_RechargeBill::RechargeActivityEnd) {
            if ($type == Application_Model_PayBill::TYPE_RECHANGE && $money >= 1000 &&  $requestCode == $defalutCode) {
                $desc = "五月狂欢充值" . $desc;
            }
        }
        return $desc;
    }

    /**
     * 支付成功 
     */
    public function returnAction() {
        $pid = $this->getRequest()->getParam('out_trade_no');
        $this->_helper->redirector('success', 'pay', null, array('pid' => $pid));
    }

    /**
     * 支付成功 
     */
    public function successAction() {
        $this->appendCss('/css/home/pay.css');
        $this->setTitle('付款成功');
        $pid = $this->getSafeParam('pid');
        $this->view->bill = Application_Model_PayBill::load($pid);
    }

    /**
     * 取消支付 
     */
    public function cancelAction() {
        $this->appendCss('/css/home/pay.css');
        $this->setTitle('取消付款');
        $pid = $this->getSafeParam('pid');
        $this->view->bill = Application_Model_PayBill::load($pid);
    }

    protected function _addTransaction($trade_no, $paybill, $periodStart, $account) {
        $classData = array(
            self::TYPE_RECHANGE => 'Rechange',
            self::TYPE_ORDER => 'Order',
            self::TYPE_WAYBILL => 'Waybill',
            Application_Model_PayBill::TYPE_AGENT_PAY => 'Agentpay',
            Application_Model_PayBill::TYPE_Visiting => 'Visiting',
            Application_Model_PayBill::TYPE_REPAY_LINK => 'Repaylink'
        );
        if (isset($classData[$paybill->Type])) {
            $className = $classData[$paybill->Type];
     
            require_once(APPLICATION_PATH . '/../library/finance/' . $className . '.php');
            // 对接财务模块
            try {
                $api = new $className($trade_no, $paybill, $periodStart, $account);
                $api->addTransaction();
            } catch (Exception $ex) {
                echo $ex->getMessage();
            }
        }
    }

}
